<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer editPage" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_universalChange_edit.png" class="logo" style="width: 55px;height: 55px">
          <div class="content" :title="model.projectname">
            <p>
              <b v-if="model.id || projectinfo.projectcode">{{ model.projectname + '-' }}</b>
              <b>项目变更</b>
            </p>
            <p class="light" v-show="model.id || projectinfo.projectcode">
              <span>申请人：{{ model.username + '【' + model.usercode + '】' }}</span>
              <span v-if="model.id">创建时间：{{ formatDate(model.createon) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list">
          <template v-for="(item) in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="mpmMainContainer">
          <div style="padding:0 10px">
            <!-- 项目经理选择显示 -->
            <el-form v-if="extraParam === 'Manager'" class="tl-form" style="margin-top: 20px" ref="selectapprovalform" :model="model" :rules="rules" label-width="120px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="选择审批人">
                    <tl-ref-user v-model="addapprovalusercodes" :initDisplayData.sync="addapprovalusernames" dataType="code" :singleSelect="false">
                    </tl-ref-user>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit||disableSave">
              <a id="basic" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                变更信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectname">
                    <el-input v-model="model.projectname" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="变更编号" prop="changecode">
                    <el-input v-model="model.changecode" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="变更内容" prop="changecontent" :rules="rules.validateRequire">
                    <el-input v-model="model.changecontent" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="变更原因" prop="changereason" :rules="rules.validateRequire">
                    <el-input v-model="model.changereason" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="对项目影响" prop="influence" :rules="rules.validateRequire">
                    <el-input v-model="model.influence" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目经理意见" prop="projectmanageropinion">
                    <el-input v-model="model.projectmanageropinion" type="textarea" :rows="4" maxlength="1000" show-word-limit disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目Owner意见" prop="owneropinion">
                    <el-input v-model="model.owneropinion" type="textarea" :rows="4" maxlength="1000" show-word-limit disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="相关方意见" prop="stakeholderopinion">
                    <el-input v-model="model.stakeholderopinion" type="textarea" :rows="4" maxlength="1000" show-word-limit disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="line" style="margin-top:0px;" v-if="model.id">&nbsp;</div>
              <a id="apply" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                申请信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
                    <el-input v-model="model.username" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人部门" prop="applydeptname">
                    <el-input v-model="model.deptname" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人公司" prop="applyorgname">
                    <el-input v-model="model.orgname" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="float: right; margin-top: 10px">
              <el-button @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked" type="primary">保存</el-button>
              <el-button @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary">
                <svg-icon icon-class="send" />提交审批
              </el-button>
              <tl-attachment ref="attachmentRef" sourceType="MpmProjectUniversalChange" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : ''}}
                  [{{ this.$refs.attachmentRef ? ( this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount ) : 0 }}]
                </el-button>
              </tl-attachment>
              <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary">
                <svg-icon icon-class="list" />审批历史
              </el-button>
              <el-button @click="doDelApproval" v-if="!disableEditSubmit" :disabled="disableDelApproval" type="primary">
                <svg-icon icon-class="undo" />取消审批
              </el-button>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <tl-approval-history ref="history" sourceType="MpmProjectUniversalChange" :sourceId="model.id" />
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
/** 工具类 */
import { formatDate } from '@tapui/utils/date'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: {},
  data() {
    return {
      moduleTitle: '项目变更通用',
      urlPrefix: '/mpm/projectUniversalChange/',
      url: {
        // 额外的url
        saveApprovalUserAndOpinion: '/mpm/projectUniversalChange/saveApprovalUserAndOpinion'
      },
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      loading: false,
      listMode: true,
      mainHeight: 1000,
      mainScrollElement: null,
      navList: [
        { name: '立项信息', on: true, code: 'basic' },
        { name: '申请信息', on: false, code: 'apply' }
      ],
      // 审批节点配置的额外参数
      extraParam: '',
      // 判断是否是审批组件调用
      fromApproval: '',
      // 选择审批人code
      addapprovalusercodes: '',
      // 选择审批人name
      addapprovalusernames: ''
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    },
    projectinfo: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'orgname', this.org.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        // 变更类型为其他
        this.$set(this.model, 'sourcetype', 'MpmProjectUniversalChange')
      }
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace('ending', '')
      this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    loaded() {
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date ? date.toString().replace(/\-/g, "/") : date), "yyyy-MM-dd")
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then(_ => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
          // 判断是否可以将项目信息自动填写在单据中
          if (this.projectinfo.id) {
            this.setProjectInfo(this.projectinfo)
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        }
        this.mainScrollElement = document.getElementById('mpmMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
      })
    },
    /** 点击左侧导航，抽屉组件必有 **/
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      this.mainScrollElement.addEventListener('scroll', () => {
        let currentTop = this.mainScrollElement.scrollTop
        let code = ''
        for (let element of document.getElementsByClassName('step-position')) {
          if (element.getBoundingClientRect().y >= 0) {
            code = element.id
            break
          }
        }
        this.navList.forEach((m) => {
          if (m.code === code) {
            m.on = true
          } else {
            m.on = false
          }
        })
      })
    },
    /** 新增状态下把项目信息自动填写到单据中 **/
    setProjectInfo() {
      this.$set(this.model, 'projectname', this.projectinfo.projectname)
      this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
      this.$set(this.model, 'projectmanager', this.projectinfo.projectmanager)
      this.$set(this.model, 'projectmanagercode', this.projectinfo.projectmanagercode)
    },
    /** 选择审批人节点保存项目经理意见和审批人 **/
    saveApprovalUserAndOpinion(resolve, reject) {
      // 如果没选择审批人则不调该接口
      if (this.addapprovalusercodes) {
        let params = {
          applyid: this.model.id,
          opinion: this.$parent.$parent.$parent.approvalopinion,
          addapprovalusercodes: this.addapprovalusercodes,
          addapprovalusernames: this.addapprovalusernames
        }
        putAction(this.url.saveApprovalUserAndOpinion, params)
          .then(res => {
            if (res.success) {
              this.$emit('refresh')
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
          .catch(err => {
            this.$tap.alert('提交审批失败，请联系系统管理员', 'warning')
            reject()
          })
      } else {
        resolve()
      }
    },
    /** 选择审批人节点退回时保存项目经理意见 **/
    saveManagerBackOpinion(resolve, reject) {
      let params = {
        applyid: this.model.id,
        opinion: this.$parent.$parent.$parent.approvalopinion
      }
      putAction(this.url.saveApprovalUserAndOpinion, params)
        .then(res => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('提交审批失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    /** 项目经理确认节点保存审批人 **/
    saveApprovalUser(resolve, reject) {
      // 如果没选择审批人则不调该接口
      if (this.addapprovalusercodes) {
        let params = {
          applyid: this.model.id,
          addapprovalusercodes: this.addapprovalusercodes,
          addapprovalusernames: this.addapprovalusernames
        }
        putAction(this.url.saveApprovalUserAndOpinion, params)
          .then(res => {
            if (res.success) {
              this.$emit('refresh')
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
          .catch(err => {
            this.$tap.alert('提交审批失败，请联系系统管理员', 'warning')
            reject()
          })
      } else {
        resolve()
      }
    }
  },
  created() {
    // 抽屉组件必有
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    // 抽屉组件必有
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>

